package com.xiangxiao.rpan.storage.download.stream;

import com.xiangxiao.rpan.storage.core.DownloadFileTool;
import com.xiangxiao.rpan.storage.core.DownloadFileTool;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/12/1 17:41
 */
@Component(value = "downloadFileInAndOutStream")
public class DownloadFileInAndOutStream implements DownloadFileTool {
  @Override
  public void readStreamToFile(String path, HttpServletResponse response) {
    try {
      File file = new File(path);
      String filename = file.getName();

      InputStream inStream = new FileInputStream(path);
      response.reset();
      response.setContentType("bin");
      response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
      // 循环取出流中的数据
      byte[] b = new byte[100];
      int len;
        while ((len = inStream.read(b)) > 0)
          response.getOutputStream().write(b, 0, len);
        inStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public String convertMuitlFileToStream(MultipartFile multipartFile, Integer chunkNumber, Integer totalChunks, long blockSize) {
    return null;
  }
}
